<?php
declare (strict_types=1);

namespace app\common\controller;

use app\BaseController;
use app\common\model\AdminLoginLogModel;
use app\common\model\AdminLogModel;
use app\common\service\AdminMenuService;
use app\common\service\SysConfService;
use think\facade\Cache;

/*后台 - 登录后继承的控制器*/

class AdminLogin extends BaseController
{

    protected $page_size = 20; //后台每页默认显示的数据条数

    protected $menu_name = [ //未知菜单默认值
        0 => '未知',
        1 => '未知',
        2 => '未知',
        'id' => 0
    ];

    public function initialize()
    {
        parent::initialize();

        //获取用户当前菜单的名称
        $this->menu_name = AdminMenuService::ins()->getMenuName(menu_url());
        $this->assign('menu_name_list', $this->menu_name);
        $page_size = cookie('page_size');
        if (!empty($page_size)) {
            $this->page_size = (int)$page_size;
        }
    }

    //后置,记录用户的访问日志信息
    public function __destruct()
    {
        $this->adminLog(); //记录用户的访问和操作日志
    }


    /*
     * @title 获取分页的信息
     * */
    protected final function pageInfo(): array
    {
        $page = $this->request->param('p', 1, 'intval');
        if (intval($page) < 1) {
            $page = 1;
        }
        $limit = ($page - 1) * $this->page_size;
        return [$page, $limit];
    }

    /*
     * @title 记录用户的操作和访问日志 (并发量大时,可以考虑异步方式)
     * */
    public function adminLog(): bool
    {
        $url = menu_url();
        if (in_array($url, config('app.admin_common_menu')) || in_array('未知', $this->menu_name)) { //公共的action不记录日志,没有添加到系统菜单中的不记录
            return false;
        }
        $data = [];
        if (empty($this->request->user_info)) return false;
        $data['uid'] = $this->request->user_info['uid'];
        $data['menu_name'] = implode('-', $this->menu_name);
        $data['url'] = trim($url, '.html');
        $data['req_type'] = strtolower($this->request->method());
        $data['get'] = json_encode($this->request->get(), 256);
        $data['post'] = json_encode($this->request->post(), 256);
        AdminLogModel::create($data);

        //自动删除日志(每天只进行一次删除)
        $key = 'DELETE_LOG_STATUS' . date('Y_m_d');
        $result = Cache::store('redis')->get($key);
        if (!$result) {
            //删除访问日志
            $day = (new SysConfService())->getKey('VISIT_LOG_SAVE_DAY');
            if ($day > 0) {
                $date = date('Y-m-d 00:00:00', strtotime("- {$day}day"));
                AdminLogModel::where('add_time', '<', $date)->delete();
            }
            //删除登录日志
            $day = (new SysConfService())->getKey('LOGIN_LOG_SAVE_DAY');
            if ($day > 0) {
                $date = date('Y-m-d 00:00:00', strtotime("- {$day}day"));
                AdminLoginLogModel::where('login_time', '<', $date)->delete();
                Cache::store('redis')->set($key, 1, 3600 * 24);
            }
        }
        return true;
    }

    /*
     * @title 后台分页
     * @param int $cnt 数据中条数
     * */
    public function newPage(int $cnt, int $page_size, int $page): string
    {
        if ($cnt <= 0) return '';
        $map = $this->request->param();
        $url = menu_url();
        $num_p = ceil($cnt / $page_size);
        if ($num_p <= 1) return '<div><a class="prev">' . (string)$cnt . '条(1)页</a></div>';
        if (empty($page)) $page = 1;
        //首页 上一页
        $_page = '<a class="prev">' . $cnt . '条(' . $num_p . ')页</a>';
        if ($page == 1) {
            $_page .= "<a class='prev'>首页</a>";
            $_page .= "<a class='prev'>上一页</a>"; //当前页
        } else {
            $first_map = $map;
            $first_map['p'] = 1;
            $_page .= "<a class='prev' href='" . url($url, $first_map) . "' datapage='1'>首页</a>";
            $pre_page = $page - 1;
            $map['p'] = $pre_page;
            $_page .= "<a  class='prev' href='" . url($url, $map) . "' datapage='{$pre_page}'>上一页</a>";
        }
        //中间分页
        $left = max($page - 2, 1);
        $right = min($left + 4, $num_p);
        $left = max($right - 4, 1);
        for ($i = $left; $i <= $right; $i += 1) {
            if ($page == $i) {
                $_page .= "<span class='current' href='javascript:;'' datapage=$i>$i</span>";
            } else {
                $map['p'] = $i;
                $_page .= "<a href='" . url($url, $map) . "' class='num' datapage=$i>$i</a>";
            }
        }
        //下一页 尾页
        if ($page == $num_p) {
            $_page .= "<a class='prev'>下一页</a>";
            $_page .= "<a class='prev'>尾页</a>";
        } else {
            $next_page = $page + 1;
            $map['p'] = $next_page;
            $_page .= "<a  class='prev' href='" . url($url, $map) . "' datapage='{$next_page}'>下一页</a>";
            $last_map = $map;
            $last_map['p'] = $num_p;
            $_page .= "<a class='prev' href='" . url($url, $last_map) . "' datapage='" . $num_p . "'>尾页</a>";
        }
        $last_map['p'] = 'set_page';
        $_page .= "<a class='prev set_page' href='javascript:;'  page_url='" . url($url, $last_map) . "' datapage='" . $num_p . "'>跳页</a>";
        return '<div>' . $_page . '</div>';
    }

    /*
     * @title 地区搜索
     * */
    public final function areaInfo(): string
    {
        $province = $this->request->param('province', '0');
        $city = $this->request->param('city', '0');
        $area = $this->request->param('area', '0');
        $this->assign('area_info', ['province' => $province, 'city' => $city, 'area' => $area]);
        $info = $province ? $province : '0';
        $info = $city ? $city : $info;
        $info = $area ? $area : $info;
        return $info;
    }
}
